//
//  KLSoundplay.m
//  KLSoundplayDemo
//
//  Created by Coollang on 17/4/19.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "KLSoundplay.h"
#import <MediaPlayer/MediaPlayer.h>
#import "SoundManager.h"


@interface KLSoundplay ()
@property (nonatomic, assign)BOOL isPlaying;
@property (nonatomic, strong) NSArray *sounds;
// 开启后台语音
@property (nonatomic, assign) BOOL allowsBackgroundMusic;
@end

@implementation KLSoundplay {
    __block NSUInteger _indexOfSound;
    BOOL _shouldSound;
}

+ (instancetype)shareSpeedSoundplayer {
    static KLSoundplay *_instance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [KLSoundplay new];
        NSDictionary *defaultValues = [NSDictionary dictionaryWithObjectsAndKeys: @(YES), @"KLSoundplayOpenOrClose",nil];
        [[NSUserDefaults standardUserDefaults] registerDefaults:defaultValues];
    });
    return _instance;
}

- (void)setShouldSound:(BOOL)shouldSound {
    _shouldSound = shouldSound;
    [[NSUserDefaults standardUserDefaults] setBool:_shouldSound forKey:@"KLSoundplayOpenOrClose"];
}
- (BOOL)shouldSound {
    return [[NSUserDefaults standardUserDefaults] boolForKey:@"KLSoundplayOpenOrClose"];
}
- (void)soundTheSpeed:(NSUInteger)speed allowBackgroundPlay:(BOOL)allowBackplay {
    if (self.isPlaying) {
        return;
    }
    _indexOfSound = 0;
    _sounds = [self soundsWithSpeed:speed];
    self.isPlaying = YES;
    [self soundTheSpeed];
    [SoundManager sharedManager].allowsBackgroundMusic = allowBackplay;
    self.allowsBackgroundMusic = allowBackplay;
}
- (void)soundTheSpeed:(NSUInteger)speed
{
    [self soundTheSpeed:speed allowBackgroundPlay:YES];
}

- (void)soundTheSpeed
{
    if (self.shouldSound) {
        if (_indexOfSound >= [_sounds count]) {
            self.isPlaying = NO;
            return;
        }
        
        Sound *sound = _sounds[_indexOfSound];
        __weak typeof(self) weakSelf = self;
        sound.completionHandler = ^(BOOL didFinish) {
            _indexOfSound++;
            [weakSelf soundTheSpeed];
        };
        [[SoundManager sharedManager] playSound:sound];
    }
}

// 播放指定路径的音频
- (void)soundAutioWithPath:(NSURL *)voicePath allowBackgroundPlay:(BOOL)allowBackplay completionHandler:(void(^)(BOOL didFinish))completionHandler {
    if (self.shouldSound) {
        if (self.isPlaying) {
            return;
        }
        Sound *sound = [Sound soundWithContentsOfURL:voicePath];
        self.isPlaying = YES;
        __weak typeof(self) weakSelf = self;
        sound.completionHandler = ^(BOOL didFinish) {
            weakSelf.isPlaying = NO;
            if (completionHandler) {
                completionHandler(didFinish);
            }
        };
        [[SoundManager sharedManager] playSound:sound];
        [SoundManager sharedManager].allowsBackgroundMusic = allowBackplay;
        self.allowsBackgroundMusic = allowBackplay;
    }else {
        if (completionHandler) {
            completionHandler(true);
        }
    }
}

- (NSArray *)soundsWithSpeed:(NSUInteger)speed
{
    NSString *boundPath = [[NSBundle mainBundle] pathForResource:@"Sound" ofType:@"bundle"];
    NSBundle *soundBundel = [NSBundle bundleWithPath:boundPath];
    
    if ([self languageIsChinese]) {
        
        NSString *filePath = [soundBundel pathForResource:@"Sound" ofType:nil];
        NSMutableArray *soundNames = [@[@"shisu"] mutableCopy];
        NSMutableArray *sounds = [@[] mutableCopy];
        [soundNames addObjectsFromArray:[self speedSoundNameWithSpeed:speed]];
        [soundNames addObjectsFromArray:@[@"km"]];
        
        for (NSString *soundName in soundNames) {
            NSString *path = [filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.wav",soundName]];
            NSURL *url = [[NSURL alloc] initWithString:path];
            Sound *sound = [Sound soundWithContentsOfURL:url];
            [sounds addObject:sound];
        }
        
        return [sounds copy];
    } else {
        NSMutableArray *sounds = [NSMutableArray array];
        NSString *filePath = [soundBundel pathForResource:@"EnglishSound" ofType:nil];
        
        NSString *path =  [filePath stringByAppendingPathComponent:@"speed.wav"];
        NSURL *url = [[NSURL alloc] initWithString:path];
        Sound *sound = [Sound soundWithContentsOfURL:url];
        [sounds addObject:sound];
        
        path =[filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%zd.mp3",speed]];
        url = [NSURL URLWithString:path];
        sound = [Sound soundWithContentsOfURL:url];
        [sounds addObject:sound];
        
        return [sounds copy];
    }
}

- (NSArray *)speedSoundNameWithSpeed:(NSUInteger)speed
{
    NSMutableArray *speedSoundNames = [@[] mutableCopy];
    if (speed >= 100) {
        NSUInteger hundred = speed/100;
        [speedSoundNames addObjectsFromArray:@[[NSString stringWithFormat:@"%lu", (unsigned long)hundred], @"100"]];
        if (speed%100 != 0) {
            NSUInteger ten = speed%100/10;
            if (ten != 0) {
                [speedSoundNames addObjectsFromArray:@[[NSString stringWithFormat:@"%lu", (unsigned long)ten], @"10"]];
            } else {
                [speedSoundNames addObject:[NSString stringWithFormat:@"%lu", (unsigned long)ten]];
            }
            
            NSUInteger unit = speed%10;
            if (unit != 0) {
                [speedSoundNames addObject:[NSString stringWithFormat:@"%lu", (unsigned long)unit]];
            }
        }
    } else if (speed >= 10) {
        
        NSUInteger ten = speed/10;
        if (ten != 0) {
            [speedSoundNames addObjectsFromArray:@[[NSString stringWithFormat:@"%lu", (unsigned long)ten], @"10"]];
        } else {
            [speedSoundNames addObject:[NSString stringWithFormat:@"%lu", (unsigned long)ten]];
        }
        
        NSUInteger unit = speed%10;
        if (unit != 0) {
            [speedSoundNames addObject:[NSString stringWithFormat:@"%lu", (unsigned long)unit]];
        }
        
    } else {
        NSUInteger unit = speed;
        if (unit != 0) {
            [speedSoundNames addObject:[NSString stringWithFormat:@"%lu", (unsigned long)unit]];
        }
    }
    
    return [speedSoundNames copy];
}

- (BOOL)languageIsChinese {
    return NO;
//    NSArray *languages = [NSLocale preferredLanguages];
//    NSString *currentLanguage = [languages objectAtIndex:0];
//    return [currentLanguage rangeOfString:@"zh-Hans"].location != NSNotFound;
}

- (void)setAllowsBackgroundMusic:(BOOL)allow
{
    if (_allowsBackgroundMusic != allow)
    {
#if TARGET_OS_IPHONE
        _allowsBackgroundMusic = allow;
        NSError *error = nil;
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setCategory:allow? AVAudioSessionCategoryPlayback: AVAudioSessionCategorySoloAmbient error:&error];
        //        [session setCategory:allow? AVAudioSessionCategoryAmbient: AVAudioSessionCategorySoloAmbient error:NULL];
        if (error) {
            NSLog(@"获取扬声器失败：%@",error);
        }
#endif
    }
}


@end
